import { memo, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Menu } from 'antd';
import { MenuProps } from 'antd/es';
import { sideMenu } from '@/routes/menu';

const SideMenu: FC<PropsWithChildren<{ menu?: MenuProps['items'] }>> = ({
  menu = sideMenu,
}) => {
  const location = useLocation();
  const navigate = useNavigate();
  const [current, setCurrent] = useState(location.pathname);
  const onClick: MenuProps['onClick'] = (e) => {
    setCurrent(e.key);
    navigate(e.key);
  };

  const rootSubmenuKeys = ['follow', 'set', 'orders', 'store'];
  const [openKeys, setOpenKeys] = useState([] as string[]);

  const onOpenChange: MenuProps['onOpenChange'] = (keys) => {
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (rootSubmenuKeys.indexOf(latestOpenKey!) === -1) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  };

  return (
    <Menu
      onClick={onClick}
      selectedKeys={[current]}
      mode="inline"
      items={menu}
      defaultSelectedKeys={[location.pathname]}
      openKeys={openKeys}
      onOpenChange={onOpenChange}
    />
  );
};

export default memo(SideMenu);
